package com.zc.exception;

import com.zc.Enum.ErrorEnum;
import com.zc.utils.JSONResult;
import com.zc.utils.ZcExceptionUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MaxUploadSizeExceededException;

/**
 * 统一异常拦截处理
 * 可以针对异常自定义去处理捕获，返回指定的类型（json类型）到前端
 */
@ControllerAdvice
@Slf4j
public class ExceptionHandle {


    @Value("${spring.servlet.multipart.max-file-size}")
    private String maxFileSize;

    /**
     * 对于自定义异常进行捕获，自定义异常处理
     *
     * @param e
     * @return
     */
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public JSONResult returnException(Exception e) {

        BusinessException businessException = null;

        if (e instanceof BusinessException) {
            //对于自定义异常进行捕获
            businessException = (BusinessException) e;
        } else if (e instanceof MaxUploadSizeExceededException) {//FileSizeLimitExceededException
            //对于文件上传大小限制异常进行捕获
            businessException = ZcExceptionUtil.display(ErrorEnum.S_10001, maxFileSize);
        } else {
            //其他异常处理
            businessException = ZcExceptionUtil.display(ErrorEnum.S_UNKNOW_ERROR);
        }
        log.error("系统异常 {}", e);
        return JSONResult.errorMsg(businessException.getErrorCode(), businessException.getErrorCode() + " " + businessException.getErrorMsg());
    }

}
